package com.dollar.producer_consumer;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 定量刷盘
 */
public class FixedAmountFlush<E> {
    private BlockingQueue<E> queue;

    public FixedAmountFlush(int queueCapacity) {
        queue = new ArrayBlockingQueue<E>(queueCapacity);
    }

    public void put(E e) {
        try {
            //TODO 数据清洗
            queue.put(e);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    public List<E> takeSome(int amount) {
        List<E> datas = new ArrayList<>();
        try {
            E ele = queue.take();
            int already = 0;
            while (already < amount) {
                if (ele != null) {
                    datas.add(ele);
                    ele = queue.poll();
                    already++;
                }
            }
        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
        }
        return datas;
    }
}
